let db = require('../db/index')

exports.getComment = (req, res) => {
  const id = req.params.id
  const sql = 'select * from comment where article_id = ?'
  db.query(sql, id, (err, data) => {
    if (err) {
      return res.send('获取失败' + err.message)
    }
    res.send({
      code: 20000,
      data: data
    })
  })
}

exports.addComment = (req, res) => {
  const info = req.body

  const sql = 'insert into comment (article_id,content,fromUserId,fromUserName,fromUserAvatar,createTime) values (?,?,?,?,?,?)'

  const sql2 = 'select * from comment where id = ?'

  const sql3 = 'update comment set reply = ? where id = ?'

  const sql4 = 'update article set commentsCount = commentsCount + 1 where id = ?'

  if (info.toUserId === undefined) {
    db.query(sql, [info.article_id, info.content, info.fromUserId, info.fromUserName, info.fromUserAvatar, info.createTime], (err, data) => {
      if (err) {
        return res.send('添加失败' + err.message)
      }
      db.query(sql4, info.article_id, (err, data) => {
        if (err) {
          return res.send('添加失败' + err.message)
        }
        return res.send({
          code: 20000,
          data: '添加成功'
        })
      })

    })
  } else {
    db.query(sql2, info.id, (err, data) => {
      if (err) {
        return res.send('回复失败' + err.message)
      }

      let reply = JSON.parse(data[0].reply || '[]')
      let { id, ...other } = info
      reply.push(other)

      db.query(sql3, [JSON.stringify(reply), id], (err, data) => {
        if (err) {
          return res.send('回复失败' + err.message)
        }
        res.send({
          code: 20000,
          data: '回复成功'
        })
      })
    })
  }


}